package com.xzj.mybatis.core;

import org.yaml.snakeyaml.Yaml;

import java.io.InputStream;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ProjectName: SpringDemo
 * @Package: com.xzj.mybatis.core
 * @ClassName: SqlSessionFactoryBuilder
 * @Author: xzj
 * @Description:
 * @Date: 2022/7/21 10:06
 * @Version: 1.0
 */
public class SqlSessionFactoryBuilder {

    /**
     * @param in
     * @return
     * @Author xzj
     * @Description 解析配置文件并初始化连接
     * @Date 10:58 2022/7/21
     **/
    public SqlSessionFactory build(InputStream in) {
        //解析YAML文件
        Yaml yaml = new Yaml();
        Map<String, Object> map = yaml.loadAs(in, Map.class);
        Map<String, Object> dynamic = (Map) ((Map) ((Map) map.get("spring")).get("datasource")).get("dynamic");
        //解析连接池配置
        Map<String, Object> druid = (Map) dynamic.get("druid");
        //初始连接
        Integer initialSize = Integer.valueOf(druid.get("initial-size").toString());
        //最大连接
        Integer maxActive = Integer.valueOf(druid.get("max-active").toString());
        //最大等待时间
        Integer maxWait = Integer.valueOf(druid.get("max-wait").toString());
        //获取多数据源下默认值 主要连接的数据源
        String primary = dynamic.get("primary").toString();
        Map<String, Object> datasource = (Map<String, Object>) dynamic.get("datasource");
        //获取多个数据源
        Map<String, DataSourceInfo> dataSourceInfoMap = datasource.entrySet().stream()
                .collect(Collectors.toMap(entry -> entry.getKey(),
                        entry -> {
                            Map<String, Object> value = (Map<String, Object>) entry.getValue();
                            return DataSourceInfo.builder()
                                    .driverClassName(value.get("driverClassName").toString())
                                    .url(value.get("url").toString())
                                    .username(value.get("username").toString())
                                    .password(value.get("password").toString())
                                    .build();
                        }));
        //创建工厂并返回
        return DefaultSqlSessionFactory.builder()
                .initialSize(initialSize)
                .maxActive(maxActive)
                .maxWait(maxWait)
                .primary(primary)
                .dataSourceInfoMap(dataSourceInfoMap)
                .build()
                .init();
    }
}
